import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Modal,
  Form,
  Select,
  message,
  Tag,
  InputNumber,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import type { Course } from "../../../types/admin";
import { useUser } from "../../../contexts/UserContext";
import PermissionGuard from "../../../components/PermissionGuard";

const { Search } = Input;
const { confirm } = Modal;
const { TextArea } = Input;

const CourseManagement: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [courses, setCourses] = useState<Course[]>([
    {
      id: "c1",
      name: "高级Web开发",
      code: "CS301",
      description: "学习现代Web开发技术和框架",
      teacher: {
        id: "t1",
        name: "张三",
      },
      schedule: "周一 1-2节",
      location: "教学楼A-301",
      capacity: 60,
      enrolled: 45,
      status: "active",
      createTime: "2024-01-01",
    },
  ]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCourse, setEditingCourse] = useState<Course | null>(null);
  const [form] = Form.useForm();

  const handleSearch = (value: string) => {
    // TODO: 实现搜索功能
    console.log("搜索:", value);
  };

  const showEditModal = (course: Course | null) => {
    setEditingCourse(course);
    setModalVisible(true);
    if (course) {
      form.setFieldsValue(course);
    } else {
      form.resetFields();
    }
  };

  const handleDelete = (id: string) => {
    confirm({
      title: "确认删除",
      icon: <ExclamationCircleOutlined />,
      content: "确定要删除这门课程吗？此操作不可恢复。",
      onOk: async () => {
        try {
          // TODO: 调用删除API
          setCourses(courses.filter((c) => c.id !== id));
          message.success("删除成功");
        } catch (error) {
          message.error("删除失败");
        }
      },
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingCourse) {
        // TODO: 调用更新API
        setCourses(
          courses.map((c) =>
            c.id === editingCourse.id ? { ...c, ...values } : c
          )
        );
        message.success("更新成功");
      } else {
        // TODO: 调用创建API
        const newCourse: Course = {
          id: Date.now().toString(),
          ...values,
          enrolled: 0,
          createTime: new Date().toISOString().split("T")[0],
        };
        setCourses([...courses, newCourse]);
        message.success("创建成功");
      }
      setModalVisible(false);
    } catch (error) {
      message.error("提交失败");
    }
  };

  const columns = [
    {
      title: "课程名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "课程代码",
      dataIndex: "code",
      key: "code",
    },
    {
      title: "任课教师",
      dataIndex: ["teacher", "name"],
      key: "teacher",
    },
    {
      title: "上课时间",
      dataIndex: "schedule",
      key: "schedule",
    },
    {
      title: "上课地点",
      dataIndex: "location",
      key: "location",
    },
    {
      title: "选课情况",
      key: "enrollment",
      render: (_: unknown, record: Course) => (
        <span>
          {record.enrolled}/{record.capacity}
        </span>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => (
        <Tag color={status === "active" ? "green" : "red"}>
          {status === "active" ? "进行中" : "已结束"}
        </Tag>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: Course) => (
        <Space>
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PermissionGuard permission="course.manage">
      <div style={{ padding: "24px" }}>
        <Card>
          <Space direction="vertical" style={{ width: "100%" }}>
            <Space style={{ marginBottom: 16 }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => showEditModal(null)}
              >
                添加课程
              </Button>
              <Search
                placeholder="搜索课程..."
                onSearch={handleSearch}
                style={{ width: 300 }}
              />
            </Space>

            <Table
              rowKey="id"
              columns={columns}
              dataSource={courses}
              loading={loading}
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
            />
          </Space>
        </Card>

        <Modal
          title={editingCourse ? "编辑课程" : "添加课程"}
          open={modalVisible}
          onOk={handleModalOk}
          onCancel={() => setModalVisible(false)}
          destroyOnClose
          width={600}
        >
          <Form form={form} layout="vertical">
            <Form.Item
              name="name"
              label="课程名称"
              rules={[{ required: true, message: "请输入课程名称" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="code"
              label="课程代码"
              rules={[{ required: true, message: "请输入课程代码" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name={["teacher", "id"]}
              label="任课教师"
              rules={[{ required: true, message: "请选择任课教师" }]}
            >
              <Select>
                <Select.Option value="t1">张三</Select.Option>
                <Select.Option value="t2">李四</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="description"
              label="课程描述"
              rules={[{ required: true, message: "请输入课程描述" }]}
            >
              <TextArea rows={4} />
            </Form.Item>
            <Form.Item
              name="schedule"
              label="上课时间"
              rules={[{ required: true, message: "请输入上课时间" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="location"
              label="上课地点"
              rules={[{ required: true, message: "请输入上课地点" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="capacity"
              label="课程容量"
              rules={[{ required: true, message: "请输入课程容量" }]}
            >
              <InputNumber min={1} style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item
              name="status"
              label="课程状态"
              rules={[{ required: true, message: "请选择课程状态" }]}
            >
              <Select>
                <Select.Option value="active">进行中</Select.Option>
                <Select.Option value="inactive">已结束</Select.Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PermissionGuard>
  );
};

export default CourseManagement;
